<?php

namespace addons\exam\controller;

use addons\exam\enum\CommonStatus;
use addons\exam\enum\UserScoreType;
use addons\exam\library\ScoreService;
use addons\exam\model\PaperModel;
use addons\exam\model\RoomGradeModel;
use addons\exam\model\RoomModel;
use addons\exam\model\UserModel;
use app\admin\model\exam\ConfigInfoModel;
use app\admin\model\exam\NoticeModel;
use app\common\exception\UploadException;
use app\common\library\Upload;
use think\Config;

/**
 * 公共接口
 */
class Common extends Base
{
    protected $noNeedLogin = ['index', 'login'];
    protected $noNeedRight = ['*'];

    /**
     * 读取配置
     */
    public function index()
    {
        if (!$config = ConfigInfoModel::getOne()) {
            $this->error('系统未初始化配置');
        }

        // 加载配置
        $data['system'] = json_decode($config['system_config'], true);
        $data['page']   = json_decode($config['page_config'], true);
        $data['ad']     = json_decode($config['ad_config'], true);
        $data['score']  = json_decode($config['score_config'], true);
        $member_config  = json_decode($config['member_config'], true);
        $data['member'] = $member_config;

        // 加载首页数据
        $data['notice']  = NoticeModel::where('status', CommonStatus::NORMAL)->order('weigh desc')->column('name');
        $data['notices'] = NoticeModel::where('status', CommonStatus::NORMAL)->order('weigh desc')->field('id,name')->limit(5)->select();
        $data['papers'] = $this->indexPaperList();
        $data['rooms']  = $this->indexRoomList();

        // 加载用户信息
        if ($this->auth->getUser()) {
            $user         = $this->auth->getUser()->visible(['id', 'avatar', 'nickname', 'status', 'createtime', 'logintime'])->toArray();
            $user['info'] = UserModel::getInfo($this->auth->id);
            $data['user'] = $user;

            // 隐藏广告且是会员
            if (($member_config['member_show_ad'] ?? 1) == 0 && UserModel::isMember($this->auth->id)) {
                // 把所有流量主广告ID置空
                $data['ad'] = [];
            }
        }

        // 登录得积分
        $data['point']   = [
            'get_point' => ScoreService::getScore($this->auth->id, UserScoreType::LOGIN),
            'type'      => UserScoreType::getDescription(UserScoreType::LOGIN)
        ];
        $data['version'] = APP_VERSION;

        $this->success('请求成功', $data);
    }

    /**
     * 上传文件
     */
    public function upload()
    {
        Config::set('default_return_type', 'json');
        //必须设定cdnurl为空,否则cdnurl函数计算错误
        Config::set('upload.cdnurl', '');
        $chunkid = $this->request->post("chunkid");
        if ($chunkid) {
            if (!Config::get('upload.chunking')) {
                $this->error(__('Chunk file disabled'));
            }
            $action     = $this->request->post("action");
            $chunkindex = $this->request->post("chunkindex/d");
            $chunkcount = $this->request->post("chunkcount/d");
            $filename   = $this->request->post("filename");
            $method     = $this->request->method(true);
            if ($action == 'merge') {
                $attachment = null;
                //合并分片文件
                try {
                    $upload     = new Upload();
                    $attachment = $upload->merge($chunkid, $chunkcount, $filename);
                } catch (UploadException $e) {
                    $this->error($e->getMessage());
                }
                $this->success(__('Uploaded successful'), ['url' => $attachment->url, 'fullurl' => cdnurl($attachment->url, true)]);
            } elseif ($method == 'clean') {
                //删除冗余的分片文件
                try {
                    $upload = new Upload();
                    $upload->clean($chunkid);
                } catch (UploadException $e) {
                    $this->error($e->getMessage());
                }
                $this->success();
            } else {
                //上传分片文件
                //默认普通上传文件
                $file = $this->request->file('file');
                try {
                    $upload = new Upload($file);
                    $upload->chunk($chunkid, $chunkindex, $chunkcount);
                } catch (UploadException $e) {
                    $this->error($e->getMessage());
                }
                $this->success();
            }
        } else {
            $attachment = null;
            //默认普通上传文件
            $file = $this->request->file('file');
            try {
                $upload     = new Upload($file);
                $attachment = $upload->upload();
            } catch (UploadException $e) {
                $this->error($e->getMessage());
            }

            $this->success(__('Uploaded successful'), ['url' => $attachment->url, 'fullurl' => cdnurl($attachment->url, true)]);
        }
    }

    /**
     * 首页试卷列表
     * @return array
     */
    protected function indexPaperList()
    {
        $papers = PaperModel::where('status', CommonStatus::NORMAL)
            ->where('is_only_room', 0)
            ->order('join_count', 'desc')
            ->limit(6)->select();
        foreach ($papers as &$paper) {
            // 试卷参与人员
            $users = PaperModel::getJoinUsers($paper['id'], -4);
            // 参与人员头像
            $user_avatars = [];
            foreach ($users as $user) {
                $user_avatars[] = [
                    'src' => $user['avatar']
                ];
            }
            $paper['users'] = $user_avatars;
        }

        return $papers;
    }

    /**
     * 首页考场列表
     * @return array
     */
    protected function indexRoomList()
    {
        $rooms = RoomModel::where('status', CommonStatus::NORMAL)->order('grade_count', 'desc')->limit(6)->select();
        foreach ($rooms as &$room) {
            // 考场考试人员
            $users = RoomGradeModel::getJoinUsers($room['id'], -4);
            // 参与人员头像
            $user_avatars = [];
            foreach ($users as $user) {
                $user_avatars[] = [
                    'src' => $user['avatar']
                ];
            }
            $room['users'] = $user_avatars;
        }

        return $rooms;
    }
}
